//
//  MGReqManager.m
//  MoneyGoal_iOS
//
//  Created by yyb on 2022/8/23.
//  Copyright © 2022 Moneyease CO,. LTD. All rights reserved.
//

#import "MGReqManager.h"

@implementation MGReqManager

+ (MGReqManager *)shared {
    static MGReqManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[MGReqManager alloc] init];
    });
    return manager;
}

- (NSString *)avatarURL:(NSString *)avatar {
    return [NSString stringWithFormat:@"https://moneyease-icons.oss-cn-hangzhou.aliyuncs.com/%@", avatar];
}

- (NSString *)requestURL:(NSString *)router {
    return [@"http://121.40.60.71:8100/moneygoal/" stringByAppendingPathComponent:router]; // dev
}

- (instancetype)init {
    self = [super init];
    if (!self) return nil;
    
    self.configManagerBlock = ^(AFHTTPSessionManager *manager, NSString *URLString) {
        [manager.requestSerializer setValue:[NSObject shortVersion] forHTTPHeaderField:@"app_version"];
        [manager.requestSerializer setValue:@"moneygoal" forHTTPHeaderField:@"app_type"];
        [manager.requestSerializer setValue:[NSObject device_type] forHTTPHeaderField:@"device_type"];
    };
    
    self.configResultsBlock = ^BOOL(id data, NSError *error, NSDictionary *params, NSString *path, YYBResponseSuccBlock succBlock, YYBResponseErrorBlock errorBlock) {
        NSDictionary *res = (NSDictionary *)data;
        NSInteger code = [res[@"code"] integerValue];
        if (code == 200 && res) {
            NSDictionary *res_data = res[@"data"];
            if (succBlock) {
                succBlock(res_data, params);
            }
        } else {
            NSString *errorMessage = res ? res[@"message"] : @"系统错误";
            NSInteger errorCode = res ? code : 500;
            
            NSDictionary *userInfo = @{ @"message": errorMessage ? errorMessage : @"服务器出错" };
            NSError *error = [NSError errorWithDomain:@"" code:errorCode userInfo:userInfo];
            if (errorBlock) {
                errorBlock(error, params);
            }
        }
        return NO;
    };
    
    return self;
}

- (void)defaultRequestWithPath:(NSString *)path parameters:(NSDictionary *)parameters successBlock:(YYBResponseSuccBlock)successBlock errorBlock:(YYBResponseErrorBlock)errorBlock {
    [self handleRequestWithMethod:@"POST" URLString:[self requestURL:path] params:[parameters createSign] paramsInBody:YES configManagerBlock:nil configResultsBlock:nil successBlock:successBlock errorBlock:errorBlock];
}

- (void)getWechatResultWithCode:(NSString *)code successBlock:(YYBResponseSuccBlock)successBlock errorBlock:(YYBResponseErrorBlock)errorBlock {
    NSString *appId = @"wx53759a0622e4dcfc";
    NSString *secret = @"8872334701f37dd00d78d31141a2abe3";
    NSString *path = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",appId, secret, code];
    
    [self handleRequestWithMethod:@"GET" URLString:path params:nil configManagerBlock:nil configResultsBlock:^BOOL(id data, NSError *error, NSDictionary *params, NSString *path, YYBResponseSuccBlock succBlock, YYBResponseErrorBlock errorBlock) {
        [self getWechatUserInfo:data successBlock:successBlock errorBlock:errorBlock];
        return NO;
    } successBlock:nil errorBlock:^(NSError *error, NSDictionary *params) {
        if (errorBlock) {
            errorBlock(error, params);
        }
    }];
}

- (void)getWechatUserInfo:(NSDictionary *)userInfo successBlock:(YYBResponseSuccBlock)successBlock errorBlock:(YYBResponseErrorBlock)errorBlock {
    NSString *openid = userInfo[@"openid"];
    NSString *access_token = userInfo[@"access_token"];
    NSString *path = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",access_token, openid];
    
    [self handleRequestWithMethod:@"GET" URLString:path params:nil configManagerBlock:nil configResultsBlock:^BOOL(id data, NSError *error, NSDictionary *params, NSString *path, YYBResponseSuccBlock succBlock, YYBResponseErrorBlock errorBlock) {
        [self wx_loginWithUserInfo:userInfo userData:data successBlock:successBlock errorBlock:errorBlock];
        return NO;
    } successBlock:nil errorBlock:^(NSError *error, NSDictionary *params) {
        if (errorBlock) {
            errorBlock(error, params);
        }
    }];
}

- (void)wx_loginWithUserInfo:(NSDictionary *)userInfo userData:(NSDictionary *)userData successBlock:(YYBResponseSuccBlock)successBlock errorBlock:(YYBResponseErrorBlock)errorBlock {
    NSMutableDictionary *parameters = [userData.yy_modelToJSONObject mutableCopy];
    [parameters setObject:userInfo[@"openid"] forKey:@"open_id"];
    [parameters removeObjectForKey:@"privilege"];
    
    [self defaultRequestWithPath:@"user/get/wx/" parameters:parameters successBlock:successBlock errorBlock:errorBlock];
}

- (void)getAppleLoginResultWithParameters:(NSDictionary *)parameters successBlock:(YYBResponseSuccBlock)successBlock errorBlock:(YYBResponseErrorBlock)errorBlock {
    [self defaultRequestWithPath:@"user/get/apple/" parameters:parameters successBlock:successBlock errorBlock:errorBlock];
}

- (void)putUserAvatar:(NSString *)avatarKey successBlock:(YYBResponseSuccBlock)successBlock errorBlock:(YYBResponseErrorBlock)errorBlock {
    NSDictionary *parameters = @{ @"avatar": avatarKey, @"uid": [MGUserModel user].uid };
    [self defaultRequestWithPath:@"user/update/avatar/" parameters:parameters successBlock:successBlock errorBlock:errorBlock];
}

- (void)putUserNickName:(NSString *)nickName successBlock:(YYBResponseSuccBlock)successBlock errorBlock:(YYBResponseErrorBlock)errorBlock {
    NSDictionary *parameters = @{ @"nick_name": nickName, @"uid": [MGUserModel user].uid };
    [self defaultRequestWithPath:@"user/update/nickname/" parameters:parameters successBlock:successBlock errorBlock:errorBlock];
}

- (void)deleteUserWithSuccessBlock:(YYBResponseSuccBlock)successBlock errorBlock:(YYBResponseErrorBlock)errorBlock {
    NSDictionary *parameters = @{ @"uid": [MGUserModel user].uid };
    [self defaultRequestWithPath:@"user/delete/user/" parameters:parameters successBlock:successBlock errorBlock:errorBlock];
}

- (void)getCaptchaWithPhoneNum:(NSString *)phoneNum successBlock:(YYBResponseSuccBlock)successBlock errorBlock:(YYBResponseErrorBlock)errorBlock {
    NSDictionary *parameters = @{ @"phone": phoneNum };
    [self defaultRequestWithPath:@"user/captcha/get/" parameters:parameters successBlock:successBlock errorBlock:errorBlock];
}

- (void)handleLoginWithPhoneNum:(NSString *)phoneNum captcha:(NSString *)captcha successBlock:(YYBResponseSuccBlock)successBlock errorBlock:(YYBResponseErrorBlock)errorBlock {
    NSDictionary *parameters = @{ @"phone": phoneNum, @"code": captcha };
    [self defaultRequestWithPath:@"user/captcha/valid/" parameters:parameters successBlock:successBlock errorBlock:errorBlock];
}

@end
